from PySide6.QtWidgets import QMainWindow, QTabWidget, QVBoxLayout, QWidget
from .table_viewer import TableViewer

class TableWindowManager(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("表格数据")
        self.resize(800, 600)
        self._init_ui()
        self.opened_tables = {}

    def _init_ui(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        
        # 创建标签页控件
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabsClosable(True)
        self.tab_widget.tabCloseRequested.connect(self.close_tab)
        layout.addWidget(self.tab_widget)

    def open_table(self, filename):
        if filename in self.opened_tables:
            # 如果表格已打开，切换到对应标签页
            index = self.tab_widget.indexOf(self.opened_tables[filename])
            self.tab_widget.setCurrentIndex(index)
        else:
            # 创建新的表格视图
            table_view = TableViewer(filename)
            index = self.tab_widget.addTab(table_view, filename)
            self.tab_widget.setCurrentIndex(index)
            self.opened_tables[filename] = table_view
            self.show()
            self.raise_()
            # 连接数据更新信号
            table_view.data_updated.connect(self.on_data_updated)

    def close_tab(self, index):
        widget = self.tab_widget.widget(index)
        for filename, view in list(self.opened_tables.items()):
            if view == widget:
                del self.opened_tables[filename]
                break
        self.tab_widget.removeTab(index)
        widget.deleteLater()

    def on_data_updated(self, filename, data):
        if hasattr(self.parent(), 'update_visualization'):
            self.parent().update_visualization(filename, data) 